package it.trekker.upload;

import java.util.Hashtable;

import javax.naming.InitialContext;

import org.apache.log4j.Logger;
import it.trekker.upload.json.IFileLoaderFactory;

/*
 ***** JBoss 7.1 *****
 * Lookup for stateless bean:
 * 		ejb:<app-name>/<module-name>/<distinct-name>/<bean-name>!<fully-qualified-classname-of-the-remote-interface>
 * Lookup for stateless bean:
 * 		ejb:<app-name>/<module-name>/<distinct-name>/<bean-name>!<fully-qualified-classname-of-the-remote-interface?stateful>
 */

public class FileLoaderFactory implements IFileLoaderFactory {
	
	private static Logger logger = Logger.getLogger(FileLoaderFactory.class.getSimpleName());
	 
	@SuppressWarnings("unchecked")
	private static InitialContext getInitialContext()
			throws Exception {
		//Hashtable props = getInitialContextProperties(hostPort);
		Hashtable props = getInitialContextProperties();
		return new InitialContext(props);
		
	}
	@SuppressWarnings("unchecked")
	private static Hashtable getInitialContextProperties() {
		Hashtable props = new Hashtable();
		
		// For JBoss 6.1
//		props.put("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
//		props.put("java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces");
//		props.put("java.naming.provider.url", "127.0.0.1:1099");
		
		// For JBoss 7.1
//		props.put("java.naming.factory.initial", "org.jboss.as.naming.InitialContextFactory");
//		props.put("java.naming.factory.url.pkgs", "org.jboss.ejb.client.naming");
//		props.put("java.naming.provider.url", "127.0.0.1:1099");
		
		// For JBoss 7.1 remote client
		// The given user/password must be set by using the command bin/add-user.sh ﻿(or.bat).
//		props.put("java.naming.factory.initial", "org.jboss.naming.remote.client.InitialContextFactory");
		props.put("java.naming.factory.url.pkgs", "org.jboss.ejb.client.naming");
//		props.put("java.naming.provider.url", "remote://127.0.0.1:4447");
//		props.put(Context.SECURITY_PRINCIPAL, "trekker");
//		props.put(Context.SECURITY_CREDENTIALS, "123");
		
//		props.put("java.naming.provider.url", new ServerInfo().getHostAddress() + ":1099");
		
		return props;
	}

	
	public IFileLoader2Database getFileLoader() {
		try {
			InitialContext context = getInitialContext();
			// JBoss 6.1
//			IFileLoader2Database result = (IFileLoader2Database)context.lookup("TrekkerServer/FileLoader2Database/remote");
			// JBoss 7.1
			IFileLoader2Database result = (IFileLoader2Database)context.lookup("ejb:TrekkerServer/TrekkerServer.jar/JsonFile2Database!it.trekker.upload.IFileLoader2Database");
			return result;
		} catch (Exception e) {
			logger.error("Error looking up FileLoader2Database",e);
		}
		return null;
	}

}
